package com.leihub.xlfiletools.excel.controller;

import com.leihub.xlfiletools.excel.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author lei
 * @version 1.0
 * @description: TODO
 * @date 2024/7/22 21:52
 */
@RestController
public class ExcelController {

    @Autowired
    private ExcelService excelService;

    @GetMapping("/download-excel")
    public ResponseEntity<byte[]> downloadExcel() throws IOException {

        ByteArrayOutputStream byteArrayOutputStream = excelService.generateExcelReport();

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=transactions.xlsx");
        headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
        headers.add(HttpHeaders.PRAGMA, "no-cache");
        headers.add(HttpHeaders.EXPIRES, "0");

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(byteArrayOutputStream.toByteArray());
    }
}